using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weapon : MonoBehaviour
{
    public string _type;//the key to the asset
    public WeaponProperty _currentProperties;
    public WeaponProperty _initialProperties;
    public MainFrame _cruiser;
    private Rigidbody2D _mainCruiserRigidbody2D;
    public GameObject _bullet;
    private List<GameObject> _bulletPool = new List<GameObject>();
    private IEnumerator _fireColdDown;

    void Start()
    {
        _mainCruiserRigidbody2D = _cruiser.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        TurrentFollowMouse();
        if (Input.GetKeyDown(KeyCode.G))
        {
            _currentProperties = AssetsManager.AssetsManagerInstance._weapon_Dic["testWeapon"];//todo: generator
        }
    }

    private void TurrentFollowMouse()
    {
        Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
        transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 0, Vector2.SignedAngle(Vector2.up, direction)), _currentProperties.TurningSpeed / ConstValue.Scale);
    }

    public void Fire()
    {
        if (_fireColdDown == null)
        {
            _cruiser.ON_Attack();
            _fireColdDown = FireColdDown();
            StartCoroutine(_fireColdDown);
        }
    }

    private IEnumerator FireColdDown()
    {
        GenerateBullet();
        float frameCount = _currentProperties.FireRate;
        while (frameCount > 0)
        {
            frameCount--;
            yield return null;
        }
        StopCoroutine(_fireColdDown);
        _fireColdDown = null;
    }

    private void GenerateBullet()
    {
        for (int i = 0; i < _bulletPool.Count; i++)
        {
            if (!_bulletPool[i].activeInHierarchy)
            {
                _bulletPool[i].SetActive(true);
                _bulletPool[i].GetComponent<Bullet>().InitializeBullet(_mainCruiserRigidbody2D.velocity, gameObject, _cruiser);
                return;
            }
        }
        GameObject tempBullet = Instantiate(_bullet);
        tempBullet.GetComponent<Bullet>().InitializeBullet(_mainCruiserRigidbody2D.velocity/* - new Vector2(_rigidbody2D.angularVelocity * _turrent.transform.position.y, 0)*/, gameObject, _cruiser);
        _bulletPool.Add(tempBullet);
    }
}
